<?php

require 'i18nTwigExt.php';

class Internal_Twig_View extends Zend_View_Abstract
{
    private $_twig  = NULL;

    public function __construct($scriptPath)
    {
        parent::__construct(array('scriptPath' => $scriptPath));

        $loader = new Twig_Loader_Filesystem($scriptPath);
        $this->_twig =
            new Twig_Environment(   
                                    $loader,
                                    iterator_to_array(
                                        Zend_Registry::get('config')->twig)
                                );
        // i18nTwigExt
        $oI18nTwigExt = new i18nTwigExt();
        $this->_twig->addExtension($oI18nTwigExt);
        $this->_twig->addFunction(
                        'dict', 
                        new Twig_Function_Method($oI18nTwigExt, 'dict'));
    }
    
    public function getEngine()
    {
        return $this->_twig;
    }
    
    protected function _run()
    {   
        if (func_num_args() === 0 ||
            ! func_get_arg(0) instanceof Twig_Template)
        {
            throw new InvalidArgumentException('Its not a Twig_Template instance!');
        }
        echo func_get_arg(0)->render($this->getVars());
    }
    
    protected function _script($name)
    {  
        if (file_exists($name))
            throw new InvalidArgumentException("{$name} file is not exists!");
        return $this->_twig->loadTemplate($name);
    }
    
    public function addBasePath($path, $classPrefix = 'Zend_View')
    {
        $this->_twig->getLoader()->addPath($path . '/scripts');
        
        parent::addBasePath($path, $classPrefix);
        return $this;
    }
    
    public function setBasePath($path, $classPrefix = 'Zend_View')
    {
        $this->_twig->getLoader()->setPaths($path . '/scripts');
        
        parent::setBasePath($path, $classPrefix);
        return $this;
    }
    
    public function loadTemplate($name)
    {
        $this->_twig->loadTemplate($name);
    }
}